#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <strings.h>
#include <string.h>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Common.hpp"

class InetAddr
{
public:
    InetAddr() {}
    // 网络转主机
    InetAddr(struct sockaddr_in &addr) : _addr(addr)
    {
        _port = ntohs(addr.sin_port);
        // _ip = inet_ntoa(addr.sin_addr);
        char ipbuffer[64];
        inet_ntop(AF_INET, &addr.sin_addr, ipbuffer, sizeof(_addr));
        _ip = ipbuffer;
    }
    // 主机转网络,传ip和port
    InetAddr(const std::string &ip, uint16_t port) : _ip(ip), _port(port)
    {
        memset(&_addr, 0, sizeof(_addr));
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(port);
    }
    // 主机转网络,传port
    InetAddr(uint16_t port) : _ip(), _port(port)
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_addr.s_addr = INADDR_ANY;
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(port);
    }
    bool operator==(const InetAddr &client)
    {
        return client._ip == _ip && client._port == _port;
    }
    struct sockaddr *GetAddr()
    {
        return (sockaddr *)&_addr;
    }
    socklen_t GetAddrLen()
    {
        return sizeof(_addr);
    }
    const struct sockaddr_in &NetAddr() { return _addr; }
    std::string StringAddr()
    {
        return _ip + ":" + std::to_string(_port);
    }
    std::string GetIp()
    {
        return _ip;
    }
    uint16_t GetPort()
    {
        return _port;
    }

private:
    std::string _ip; // 点分十进制
    uint16_t _port;
    struct sockaddr_in _addr;
};